<?php

// ==============================================================================
//
// This file is part of the WelSpeak.
//
// Create by Welfony Support <support@welfony.com>
// Copyright (c) 2012-2014 welfony.com
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
// ==============================================================================

use Imagine\Image\Box;
use Imagine\Gd\Imagine;
use Imagine\Image\Point;
use Welfony\Welspeak\Core\Enum\InviteStatus;
use Welfony\Welspeak\File\FileUtility;
use Welfony\Welspeak\Repository\FriendRepository;
use Welfony\Welspeak\Repository\InviteRepository;
use Welfony\Welspeak\Repository\UserRepository;
use Welfony\Welspeak\Utility\Validation;
use Welfony\Welspeak\Utility\Util;

$app->get('/users', function() use($app) {
    $page = intval($app->request->get('page'));
    $page = $page <= 0 ? 1 : $page;
    $pageSize = intval($app->request->get('pageSize'));
    $pageSize = $pageSize <= 0 ? 20 : $pageSize;

    $totalUsersCount = UserRepository::getAllUsersCount();
    $users = UserRepository::getAllUsers($page, $pageSize);

    sendResponse(array('total' => $totalUsersCount, 'users' => $users));
});

$app->get('/users/:userId/friends', function($userId) use($app) {
    $friends = FriendRepository::getAllFriendsByUser($userId);

    $result = array();

    foreach ($friends as $friend) {
        $friend['InviteId'] = '0';
        unset($friend['ProfileBackgroundUrl']);
        $result[] = $friend;
    }

    sendResponse($result);
})->conditions(array('userId' => '\d{1,10}'));

$app->get('/users/:userId/invites', function($userId) use($app) {
    sendResponse(InviteRepository::getAllInviteByUser($userId));
})->conditions(array('userId' => '\d{1,10}'));

$app->post('/users/:userId/invites', function($userId) use($app) {
    $reqDataList = getDataFromRequestWithJsonFormat();

    $resultData = array();

    foreach ($reqDataList as $reqData) {
        if (!isset($reqData['socialId']) || empty($reqData['socialId'])) {
            continue;
        }
        if (!isset($reqData['socialType']) || intval($reqData['socialType']) <= 0) {
            continue;
        }

        $socialId = htmlspecialchars($reqData['socialId']);
        $socialType = isset($reqData['socialType']) ? intval($reqData['socialType']) : SocialType::Facebook;

        $user = UserRepository::findUserById($userId);
        if ($user['SocialExternalId'] == $socialId && $user['SocialType'] == $socialType) {
            continue;
        }

        $friend = FriendRepository::FindFriendsByUserAndSocial($userId, $socialId, $socialType);
        if ($friend) {
            continue;
        }

        $invite = array(
            'InvitorId' => $userId,
            'PIN' => $user['PIN'],
            'SocialExternalId' => $socialId,
            'SocialType' => $socialType,
            'Status' => InviteStatus::Pending,
            'CreatedDate' => date('Y-m-d H:i:s')
        );

        $newInviteId = InviteRepository::save($invite);
        if ($newInviteId) {
            $invite['InviteId'] = $newInviteId;

            $resultData[] = $invite;
        }
    }

    sendResponse($resultData);

})->conditions(array('userId' => '\d{1,10}'));

$app->put('/users/:userId/invites', function($userId) use($app) {
    $reqData = getDataFromRequestWithJsonFormat();

    if (!isset($reqData['inviteStatus']) || intval($reqData['inviteStatus']) <= 0) {
        sendInvalidFieldResult('Invite', 'inviteStatus', 'missing_field');
    }
    if (!isset($reqData['pin']) || empty($reqData['pin'])) {
        sendInvalidFieldResult('Invite', 'pin', 'missing_field');
    }

    $user = UserRepository::findUserById($userId);
    if (!$user) {
        sendOperationFailedResult('User');
    }

    $invite = InviteRepository::findInviteByPIN(htmlspecialchars($reqData['pin']), $user['SocialExternalId'], $user['SocialType']);
    if (!$invite) {
        sendResponse(array('success' => false, 'message' => 'Invalid PIN!'));
    }

    $invite['Status'] = intval($reqData['inviteStatus']);
    $invite['LastModifiedDate'] = date('Y-m-d H:i:s');
    if (!InviteRepository::update($invite['InviteId'], $invite)) {
        sendOperationFailedResult('Invite');
    }

    $existedFriend = FriendRepository::findFriendByTwoIds($invite['InvitorId'], $userId);
    if ($existedFriend) {
        sendResponse(array('success' => true, 'friend' => $existedFriend['InvitorUsername']));
    }

    $friend = array(
        'InvitorId' => $invite['InvitorId'],
        'UserId' => $userId,
        'CreatedDate' => date('Y-m-d H:i:s')
    );
    $newFriendId = FriendRepository::save($friend);
    if ($newFriendId > 0) {
        $invitor = UserRepository::findUserById($invite['InvitorId']);
        sendResponse(array('success' => true, 'friend' => $invitor['Username']));
    } else {
        sendOperationFailedResult('Friend');
    }

})->conditions(array('userId' => '\d{1,10}'));

$app->put('/users/:userId/invites/:inviteId', function($userId, $inviteId) use($app) {
    $reqData = getDataFromRequestWithJsonFormat();

    if (!isset($reqData['inviteStatus']) || intval($reqData['inviteStatus']) <= 0) {
        sendInvalidFieldResult('Invite', 'inviteStatus', 'missing_field');
    }

    $invite = InviteRepository::findInviteById($inviteId);
    if (!$invite) {
        sendOperationFailedResult('Invite');
    }

    $invite['Status'] = intval($reqData['inviteStatus']);
    $invite['LastModifiedDate'] = date('Y-m-d H:i:s');
    if (!InviteRepository::update($inviteId, $invite)) {
        sendOperationFailedResult('Invite');
    }

    $existedFriend = FriendRepository::findFriendByTwoIds($invite['InvitorId'], $userId);
    if ($existedFriend) {
        sendResponse(array('success' => true));
    }

    $friend = array(
        'InvitorId' => $invite['InvitorId'],
        'UserId' => $userId,
        'CreatedDate' => date('Y-m-d H:i:s')
    );
    $newFriendId = FriendRepository::save($friend);
    if ($newFriendId > 0) {
        sendResponse(array('success' => true));
    } else {
        sendOperationFailedResult('Friend');
    }

})->conditions(array('userId' => '\d{1,10}', 'inviteId' => '\d{1,10}'));


$app->post('/users/:userId/avatar', function($userId) use($app) {
    $user = UserRepository::findUserById($userId);
    if (!$user) {
        sendResponse(array('success' => false, 'message' => 'User is not existing!'));
    }

    if (empty($_FILES)) {
        sendResponse(array('success' => false, 'message' => 'No file found!'));
    }

    $file = $_FILES["avatar"];
    if ($file['error'] > 0) {
        sendResponse(array('success' => false, 'message' => $file['error']));
    }

    $fileName = $file['name'];
    $hashFileName = base64_encode(date('Ymdhis') . uniqid());

    $temp = explode('.', $file['name']);
    $extension = end($temp);

    if (!Validation::isValidPicture($file)) {
        sendResponse(array('success' => false, 'message' => 'File type is invalid!'));
    }

    FileUtility::createDirs($app->config['app']['avatar_path'], $userId);
    $fileTmpPath = $file['tmp_name'];
    $fileTargetPath = implode(DS, array($app->config['app']['avatar_path'], $userId, $hashFileName . '.' . $extension));
    move_uploaded_file($fileTmpPath, $fileTargetPath);

    $imagine = new Imagine();
    $image = $imagine->open($fileTargetPath);
    $image->thumbnail(new Box(180, 180))->save($fileTargetPath);

    $data = array(
        'AvatarUrl' => $app->config['app']['asset_base_url'] . implode('/', array('avatar', $userId, $hashFileName . '.' . $extension)),
        'LastModifiedDate' => date('Y-m-d H:i:s')
    );
    $success = UserRepository::update($user['UserId'], $data);
    if (!$success) {
        sendResponse(array('success' => false, 'message' => 'Operation failed!'));
    }

    sendResponse(array('success' => true, 'url' => $data['AvatarUrl']));
})->conditions(array('userId' => '\d{1,10}'));

$app->put('/users/:userId', function($userId) use($app) {
    $reqData = getDataFromRequestWithJsonFormat();

    if (!isset($reqData['username']) || empty($reqData['username'])) {
        sendInvalidFieldResult('User', 'username', 'missing_field');
    }

    $username = $reqData['username'];

    $user = UserRepository::findUserById($userId);
    if (!$user) {
        sendOperationFailedResult('User');
    }

    $updateUser = array(
        'UserId' => $userId,
        'Username' => $username,
        'LastModifiedDate' => date('Y-m-d H:i:s')
    );

    if (UserRepository::update($userId, $updateUser)) {
        sendResponse(array('success' => true));
    } else {
        sendOperationFailedResult('User');
    }

})->conditions(array('userId' => '\d{1,10}'));

$app->post('/users/:userId/remove/friends', function($userId) use($app) {
    $reqData = getDataFromRequestWithJsonFormat();
    foreach ($reqData as $data) {
        FriendRepository::removeByInvitorAndUser($userId, $data['InvitorId']);
        InviteRepository::removeByInvitorAndUser($userId, $data['InvitorId']);
    }
    sendResponse(array('success' => true));
})->conditions(array('userId' => '\d{1,10}'));

